package com.ruoyi.user.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.user.domain.Users;
import com.ruoyi.user.domain.vo.UserProfileUpdateVO;
import com.ruoyi.user.service.IUsersService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 用户Controller
 * 
 * @author ruoyi
 * @date 2025-10-21
 */
@RestController
@RequestMapping("/user/users")
public class UsersController extends BaseController
{
    @Autowired
    private IUsersService usersService;

    /**
     * 查询用户列表
     */
    @PreAuthorize("@ss.hasPermi('user:users:list')")
    @GetMapping("/list")
    public TableDataInfo list(Users users)
    {
        startPage();
        List<Users> list = usersService.selectUsersList(users);
        return getDataTable(list);
    }

    /**
     * 导出用户列表
     */
    @PreAuthorize("@ss.hasPermi('user:users:export')")
    @Log(title = "用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Users users)
    {
        List<Users> list = usersService.selectUsersList(users);
        ExcelUtil<Users> util = new ExcelUtil<Users>(Users.class);
        util.exportExcel(response, list, "用户数据");
    }

    /**
     * 获取用户详细信息
     */
    @PreAuthorize("@ss.hasPermi('user:users:query')")
    @GetMapping(value = "/{customerId}")
    public AjaxResult getInfo(@PathVariable("customerId") Long customerId)
    {
        return success(usersService.selectUsersByCustomerId(customerId));
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('user:users:add')")
    @Log(title = "用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Users users)
    {
        return toAjax(usersService.insertUsers(users));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('user:users:edit')")
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Users users)
    {
        return toAjax(usersService.updateUsers(users));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('user:user:remove')")
    @Log(title = "用户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{customerIds}")
    public AjaxResult remove(@PathVariable Long[] customerIds)
    {
        return toAjax(usersService.deleteUsersByCustomerIds(customerIds));
    }

    /**
     * 根据用户ID查询用户个人资料
     */
    @GetMapping("/profile/{customerId}")
    public AjaxResult getUserProfile(@PathVariable("customerId") Long customerId)
    {
        Users user = usersService.selectUserProfileByCustomerId(customerId);
        if (user != null) {
            return AjaxResult.success(user);
        } else {
            return AjaxResult.error("用户不存在");
        }
    }

    /**
     * 更新用户个人资料
     * 同时更新users表和sys_user表中的对应字段，包括将sys_user的username更新为手机号
     */
    @Log(title = "用户个人资料", businessType = BusinessType.UPDATE)
    @PutMapping("/profile/{customerId}")
    public AjaxResult updateUserProfile(@PathVariable("customerId") Long customerId, 
                                       @RequestBody UserProfileUpdateVO profileUpdateVO)
    {
        // 验证用户是否存在
        Users existingUser = usersService.selectUserProfileByCustomerId(customerId);
        if (existingUser == null) {
            return AjaxResult.error("用户不存在");
        }

        // 创建Users对象用于更新
        Users users = new Users();
        users.setCustomerId(customerId);
        users.setUserId(existingUser.getUserId()); // 设置userId以便同时更新sys_user表
        users.setNickname(profileUpdateVO.getNickname());
        users.setAvatarUrl(profileUpdateVO.getAvatarUrl());
        users.setGender(profileUpdateVO.getGender());
        users.setPhoneNumber(profileUpdateVO.getPhoneNumber());
        users.setExternField1(profileUpdateVO.getExternField1());
        users.setExternField2(profileUpdateVO.getExternField2());

        int result = usersService.updateUserProfile(users);
        if (result > 0) {
            return AjaxResult.success("个人资料更新成功");
        } else {
            return AjaxResult.error("个人资料更新失败");
        }
    }
}
